import { observable, action, toJS } from 'mobx';
import { message } from 'antd';
import { WeaForm } from 'comsMobx';
import { WeaLocaleProvider } from 'ecCom';
import { ValidateForm, FormatDate } from '../util';
import * as Api from '../apis/groupvoting';

const getLabel = WeaLocaleProvider.getLabel;
const initalState = {
  newGroupVoteFields: [],
  themeImage: [],
  optionInfo: {},
  voteOptions: {
    1: { key: 1, imageArr: [], imageData: [] },
    2: { key: 2, imageArr: [], imageData: [] },
  },
  newGroupVoteLoading: true,
  maxvoteoption: 2,
  finishTime: '',
  dateRef: null,
  publishLoading: false,
};
export default class NewGroupVotingStore {
  @observable newGroupVoteForm = new WeaForm();
  @observable newGroupVoteFields = initalState.newGroupVoteFields;
  @observable themeImage = initalState.themeImage;
  @observable optionInfo = initalState.optionInfo;
  @observable voteOptions = initalState.voteOptions;
  @observable newGroupVoteLoading = initalState.newGroupVoteLoading;
  @observable maxvoteoption = initalState.maxvoteoption;
  @observable finishTime = initalState.finishTime;
  @observable dateRef = initalState.dateRef;
  @observable publishLoading = initalState.publishLoading; // 发布中Loading

  @action setStoreState = (params, callback) => {
    Object.keys(params).forEach((key) => {
      this[key] = params[key];
    });
    if (callback) callback();
  }

  @action clearNewVote = () => this.setStoreState(initalState)

  // 发起新投票
  @action initiateVote = () => {
    this.newGroupVoteLoading = true;
    Api.groupvoteaddcondition().then((res) => {
      if (res.conditioninfo) {
        let nextDay = new Date(new Date().getTime() + 24 * 60 * 60 * 1000);
        this.newGroupVoteForm.initFormFields(res.conditioninfo);
        this.newGroupVoteFields = res.conditioninfo;
        this.finishTime = FormatDate(nextDay, 'yyyy-MM-dd HH:mm');
      }
      this.newGroupVoteLoading = false;
    });
  }

  /* 选项图片上传 */
  @action onOptImageChange = (ids, list, data, allList) => {
    this.voteOptions[data.key].imageArr = list;
    this.voteOptions[data.key].imageIds = ids;
    this.voteOptions[data.key].imageData = allList;
  }

  /* 删除选项图片 */
  @action deleteOptImg = (id, data) => {
    this.voteOptions[data.key].imageArr = data.imageArr.filter(v => v.fileid !== id);
    this.voteOptions[data.key].imageIds = data.imageIds.filter(v => v !== id);
    this.voteOptions[data.key].imageData = data.imageData.filter(v => v.fileid !== id);
  }

  /* 选项内容 */
  @action onOptContentChange = (value, data) => {
    this.voteOptions[data.key].content = value;
  }

  getOptionParams = () => {
    for (let v in toJS(this.voteOptions)) {
      if (!(toJS(this.voteOptions)[v].content) || toJS(this.voteOptions)[v].content === '') {
        return false;
      }
    }
  }

  // 投票发布
  @action publishVote = (params, successCallBack) => {
    ValidateForm(this.newGroupVoteForm, () => {
      this.publishLoading = true;
      let formParams = this.newGroupVoteForm.getFormParams();
      let voteoption = [];
      for (let v in toJS(this.voteOptions)) {
        let optcontent = toJS(this.voteOptions)[v].content;
        let optfileids = toJS(this.voteOptions)[v].imageIds ? (toJS(this.voteOptions)[v].imageIds).join() : '';
        voteoption = [...voteoption, { optcontent, optfileids }];
      }
      params = {
        ...formParams,
        ...params,
        groupvotename: formParams.groupvotename.trim(),
        voteoption: JSON.stringify(voteoption),
        themepic: this.themeImage[0] && this.themeImage[0].fileid || '',
        maxvoteoption: this.maxvoteoption,
        optioncount: voteoption.length,
        finishTime: this.finishTime,
        enddate: this.finishTime.split(' ')[0],
        endtime: this.finishTime.split(' ')[1],
      };
      Api.groupchatvoteadd(params).then((res) => {
        if (res.api_status === 'success') {
          message.success(getLabel('513696', '发布成功!'));
          if (typeof (successCallBack) === 'function') successCallBack(res);
        } else {
          message.error(getLabel('516191', '发布失败，请重试！'));
        }
        this.publishLoading = false;
      });
    });
  }
}
